package com.wing.purchase.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.purchase.model.request.SupplierDetailExcelInForm;
import com.wing.purchase.model.response.SupplierInfoVO;
import com.wing.purchase.service.SupplierDueService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.purchase.model.entity.SupplierInfo;
import com.wing.purchase.model.request.SupplierInfoForm;
import com.wing.purchase.service.SupplierInfoService;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-供应商表管理-待审核", tags = "#/purchase/supplierInfo")
@RestController("supplierInfoController")
@RequestMapping("purchase/admin/supplierInfo")
@RequiredArgsConstructor
@Slf4j
public class SupplierInfoController {

    private final SupplierInfoService supplierInfoService;
    private final SupplierDueService supplierDueService;


    @ApiOperation(value = "查询所有供应商表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<SupplierInfoVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String pageIndexName
            ,String corporateName
    ){
        Page<SupplierInfoVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        if (StrUtil.isNotEmpty(pageIndexName)) {
            params.put("pageIndexName", pageIndexName);
        }

        if (StrUtil.isNotEmpty(corporateName)) {
            params.put("corporateName", corporateName);
        }

        IPage<SupplierInfoVO> list =  supplierInfoService.pageList4app(pg,params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "添加供应商表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(SupplierInfoForm.Add.class) SupplierInfoForm supplierInfoForm) {
        supplierInfoForm.setStatus(SupplierInfo.Status.pending);
        if (supplierInfoForm.getSourceType()==null) {
            supplierInfoForm.setSourceType(SupplierInfo.SourceType.backstage);
        }
        if (supplierInfoService.add(supplierInfoForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改供应商表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(SupplierInfoForm.Update.class) SupplierInfoForm supplierInfoForm) {
        SupplierInfo supplierInfo = supplierInfoService.getById(supplierInfoForm.getId());
        if(supplierInfo == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(SupplierInfo.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(supplierInfoForm, supplierInfo, copyOptions);

        String cjtSupplierId = supplierInfoService.updateAndSaveCjtSupplier(supplierInfoForm,"edit");
        if (supplierInfoService.updateById(supplierInfo)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除供应商表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "supplierInfoId", value = "供应商表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long supplierInfoId) {
        //删除供应商 尽调信息一起删除
        if (supplierInfoService.removeById(supplierInfoId)) {
            supplierDueService.removeBySupId(supplierInfoId);
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "审核供应商", notes = "审核")
    @GetMapping("/audit")
    public JsonResult audit (@RequestParam("id") Long id){
        SupplierInfo supplierInfo = supplierInfoService.getById(id);
        if(supplierInfo == null){
            return JsonResult.fail("审核失败！");
        }
        if(supplierInfo.getStatus().getValue() != SupplierInfo.Status.pending.getValue()){
            return JsonResult.fail("审核失败！状态不是待审核");
        }
        supplierInfo.setStatus(SupplierInfo.Status.pass);
        supplierInfo.setAuditor(JwtUtils.getLoginUsername());
        supplierInfo.setAuditTime(LocalDateTime.now());
        if (supplierInfoService.updateById(supplierInfo)) {
            return JsonResult.success("审核成功！");
        }
        return JsonResult.fail("审核失败！");
    }




    @ApiOperation(value = "下载供应商导入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        supplierInfoService.template(response, request);
    }


    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<SupplierDetailExcelInForm> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<SupplierDetailExcelInForm> list = reader.read(is, SupplierDetailExcelInForm.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            supplierInfoService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }

}
